Introductory functions for data science


Lecture Objective:

  • Learning max() function and it's usage.

  • Learning round() function and it's usage.



In [1]:
# use python help() on max()
help(max)


Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.


In [2]:
# use help() on round()
help(round)


Help on built-in function round in module builtins:

round(...)
    round(number[, ndigits]) -> number
    
    Round a number to a given precision in decimal digits (default 0 digits).
    This returns an int when called with one argument, otherwise the
    same type as the number. ndigits may be negative.


In [5]:
# example on max
height = [ 4.5, 5.2, 6.7, 4.8, 5.6 ]

print("The tallest one is : " + str( max( height ) ) + " feets" )


The tallest one is : 6.7 feets

In [12]:
# exmple on round
some_number = 5.63

# round() with two arguments, "number" and "decimal place significance"
print("The number is rounded to: " + str( round( some_number, 1 ) ) + " with 1 decimal place of significance" )

# next, round() with only one arugment
print("\nThe number is rounded to: " + str( round( some_number ) ) + " by default" )


The number is rounded to: 5.6 with 1 decimal place of significance

The number is rounded to: 6 by default

What if while using max()there were multiple items?


In this case, the function returns the first one encountered. This remains consistent with other sort-stability preserving tools, such as sorted() and heapq().


Exercise:


1) RQ1: What is a Python function?

Ans: A piece of reusable Python code, that solves a particular problem.

2) RQ2: You have a list named x. To calculate the minimum value in this list, you use the min() function.

Which Python command should you use?

Ans: min(x)

3) RQ3: What Python command opens up the documentation from inside the IPython Shell for the min fucntion?

Ans: help(min)

4) RQ4: The function round has two arguments. Select the two correct statements about these arguments.

Ans: Number is a required argument, and ndigits is an optional argument.

Lab: Functions


Objective:

  • Use functions in different ways.
  • Experiment with different ways of specifyinng arguments.
  • How default argumetns work.

1 Familiar functions - 100xp, status: Earned


The genereal recepie for calling functions is:

`output = function_name(input)`

                 or

`variable = function_name( required arg, [ optional arg ] )` 


In [14]:
"""
Instructionns: 

        + Use print() in combination with type() to print out the type of
        var1.
        
        + Use len() to get the length of the list var1.
          Wrap it in a print() call to directly print it out.
          
        + Use int() to convert var2 to an integer. Store the output as out2.
"""

# Create variables var1 and var2
var1 = [1, 2, 3, 4]
var2 = True

# Print out type of var1
print( type( var1 ) )

# Print out length of var1
print( len( var1 ))

# Convert var2 to an integer: out2
out2 = int( var2 )
print(out2)


<class 'list'>
4
1

2. Help1 - 50xp, status: Earned

To get the help on the any function, use the following two syntax or function:

  • help( function_name )
  • ?function_name

Use the shell to open up the documentation on complex(). Which of the following statements is true?:

Ans: complex() takes two arguments, required: real number and optional: imaginary number. If only requried argument is inserted, by default the value of optional,is 0.


3. Multiple arguments -- 100xp, status: Earned

  • [] barackets around a function argument, represent an "optional argument"
  • Python also uses different way's to notify user about arg's being optional.
  • E.g. documentation of sorted() takes three arguments:

    • Iterable.

    • key, where key = None, if arg non-specified, key will be "None".

    • reverese, where reverse = False, if arg non-specified, argument by default will be "False".



In [17]:
?sorted
help(sorted)


Help on built-in function sorted in module builtins:

sorted(iterable, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customise the sort order, and the
    reverse flag can be set to request the result in descending order.


In [23]:
"""
Problem Definition:

In this exercise, you'll only have to specify "iterable" and "reverse", not key.
The first input you pass to "sorted()" will obviously be matched to the iterable argument,
but what about the second input?

To tell Python you want to specify reverse without changing anything about key,
you can use "=` :


        sorted(___, reverese = ___)
        
Two lists have been created,

        + paste them together and
        
        + sort them in "descending order".


Instructions: 

        + Use "+" to merge the contents of "first" and "second" into a new list: "full".
        
        + Call "sorted()" on "full" and specify the "reverse" argument to be "True".
        
            - Save the sorted list as "full_sorted".
            
        + Finish off by printing out "full_sorted".
"""
# Create lists first and second
first = [11.25, 18.0, 20.0]
second = [10.75, 9.50]

# Paste together first and second: full
full = list(first + second)
print("Modified list: " + str( full ) )

# Sort full in descending order: full_sorted
full_sorted = sorted( full, key = None, reverse = True )

# Print out full_sorted
print("\nThe sorted list is decending order is: " + str( full_sorted ) )


Modified list: [11.25, 18.0, 20.0, 10.75, 9.5]

The sorted list is decending order is: [20.0, 18.0, 11.25, 10.75, 9.5]